package com.intexh.quickandroid.module.chat.ui.face;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.intexh.quickandroid.R;

import java.lang.reflect.Field;
import java.util.List;


/**
 * Created by engine on 14-1-6.
 */
public class FaceAdapter extends BaseAdapter
{
    private final int imageSize;
    private List<Face> faceslist;
    private Context mContext;

    public FaceAdapter(Context context, List<Face> list)
    {
        this.mContext = context;
        this.faceslist = list;
        imageSize = context.getResources().getDimensionPixelSize(R.dimen.button_height);
    }

    @Override
    public int getCount()
    {
        return faceslist.size();
    }

    @Override
    public Face getItem(int i)
    {
        return faceslist.get(i);
    }

    @Override
    public long getItemId(int i)
    {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup)
    {
        if(view==null){
            view = LayoutInflater.from(mContext).inflate(R.layout.face_item,null);
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.faceImage);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
       // imageView.setLayoutParams(new AbsListView.LayoutParams(imageSize, imageSize));
        TextView nameText = (TextView) view.findViewById(R.id.nameView);
        Face face = getItem(i);
        if(face!=null){
            nameText.setText(face.key);
        }
        //imageView.setImageDrawable(getDrawableByAssets("yolks/"+face.value,mContext));
        Field field = null;
        try
        {
            field = R.drawable.class.getDeclaredField(face.value.split("\\.")[0]);
            //  获得资源ID的值，也就是静态变量的值
            int resourceId = Integer.parseInt(field.get(null).toString());
            imageView.setImageResource(resourceId);
        } catch (NoSuchFieldException e)
        {
            e.printStackTrace();
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }catch(OutOfMemoryError e){

        }
        return view;
    }

    public static Drawable getDrawableByAssets(String fileName, Context context)
    {

        Field field = null;
        try
        {
            field = R.drawable.class.getDeclaredField(fileName.split("\\.")[0]);
            //  获得资源ID的值，也就是静态变量的值
            int resourceId = Integer.parseInt(field.get(null).toString());
            return context.getResources().getDrawable(resourceId);
        } catch (NoSuchFieldException e)
        {
            e.printStackTrace();
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }catch(OutOfMemoryError e){

        }
        return null;
    }
}
